import {
  FC,
  ReactElement,
  useCallback,
  useEffect,
  useRef,
  useState,
} from "react";
import CheckedIcon from "../Icon/CheckedIcon";
import { Box } from "../styled";

interface IProps {
  checked?: boolean;
  onChange?: (status: boolean) => void;
}

const DebounceCheckBox: FC<IProps> = ({
  checked = false,
  onChange,
}): ReactElement => {
  const [status, setStatus] = useState<boolean>();
  const timer = useRef<NodeJS.Timeout | null>(null);

  const synchronization = useCallback(status => {
    setStatus(status);
  }, []);

  useEffect(() => {
    synchronization(checked);
  }, [checked, synchronization]);

  const handleSwitchStatus = useCallback(() => {
    setStatus(state => !state);
    if (!onChange) return;
    // 防抖 短时间(0.5s)内多次切换状态 只执行最新一次的请求
    timer.current && clearTimeout(timer.current);
    timer.current = setTimeout(() => onChange(!status), 500);
  }, [onChange, status]);

  return (
    <Box onClick={handleSwitchStatus}>
      <CheckedIcon status={status} />
    </Box>
  );
};

export default DebounceCheckBox;
